package com.chat.demo.userservice;

import com.chat.demo.auth.JwtUtils;
import com.chat.demo.userservice.DTO.User.CouldUpdateUserInfo;
import com.chat.demo.userservice.DTO.User.PasswordResetRequest;
import com.chat.demo.userservice.DTO.User.RegisterRequest;
import com.chat.demo.userservice.DTO.User.UserInfo;
import com.chat.demo.userservice.Entity.Entity.User;
import com.chat.demo.userservice.Entity.Entity.UserDao;
import jakarta.servlet.http.HttpServletRequest;
import lombok.EqualsAndHashCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;


@EqualsAndHashCode(callSuper = false)
@Service
public class User_Service {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserDao userDao;
    @Autowired
    private JwtUtils jwtUtils;

    public int register(RegisterRequest request) {
        String encodedPassword = passwordEncoder.encode(request.getPassword());
        request.setPassword(encodedPassword);
        userDao.register(request);
        return 0;
    }

    public String login(String username, String password) {
        var user = userDao.findUserByUsername(username);
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        userDao.updateLastLogin(Long.valueOf(user.getUserId()));
        userDao.updateOnlineStatus(Long.valueOf(user.getUserId()), true);
        return jwtUtils.generateToken(user.getUsername(), Long.valueOf(user.getUserId()));
    }
    public User getUserById(Long id) {
        return userDao.findUserById(id);
    }

    public UserInfo getUserInfo(Long id) {
        return userDao.findUserInfoByID(id);
    }

    public ResponseEntity<UserInfo> getUserInfoByToken(HttpServletRequest request) {
        String token = jwtUtils.getTokenFromHeader(request);
        if (token == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
        }
        try {
            String username = jwtUtils.getUsernameFromToken(token);
            User user = userDao.findUserByUsername(username);
            if (user == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
            UserInfo userInfo = getUserInfo(Long.valueOf(user.getUserId()));
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    public Boolean getUserOnlineStatus(Long id) {
        return userDao.findUserOnlineStatusByUserID(id);
    }

    public int updateUserInfo(CouldUpdateUserInfo userInfo, HttpServletRequest request) {
        String token = jwtUtils.getTokenFromHeader(request);
        String username = jwtUtils.getUsernameFromToken(token);
        Long userId = Long.valueOf(userDao.findUserByUsername(username).getUserId());
        return userDao.updateUserInfo(userInfo, userId);
    }

    public Map<String, Object> resetPassword(PasswordResetRequest requestBody, HttpServletRequest request) {
        String token = jwtUtils.getTokenFromHeader(request);
        String username = jwtUtils.getUsernameFromToken(token);
        User user = userDao.findUserByUsername(username);

        if (user == null) {
            return Map.of("status", false, "message", "用户不存在");
        }

        String oldPassword = user.getPassword();
        if (!passwordEncoder.matches(requestBody.getOldPassword(), oldPassword)) {
            return Map.of("status", false, "message", "旧密码不正确");
        }

        if (passwordEncoder.matches(requestBody.getNewPassword(), oldPassword)) {
            return Map.of("status", false, "message", "新密码不能与旧密码相同");
        }

        String encodedNewPassword = passwordEncoder.encode(requestBody.getNewPassword());
        userDao.updateUserPassword(encodedNewPassword, Long.valueOf(user.getUserId()));
        return Map.of("status", true, "message", "密码修改成功");
    }

    public Map<String, String> logout(HttpServletRequest request) {
        String token = jwtUtils.getTokenFromHeader(request);
        String username = jwtUtils.getUsernameFromToken(token);
        Long userId = Long.valueOf(userDao.findUserByUsername(username).getUserId());
        userDao.logout(userId);
        return Map.of("status", "success", "message", "logout success");
    }
}
